package com.seres.config;

import com.seres.config.entity.SysUser;
import com.seres.constant.CommonKey;
import com.seres.redis.RedisTableCache;
import com.seres.util.StringUtils;
import com.seres.vo.AuthUserInfo;
import com.seres.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Tan-Bowen
 * @version 1.0
 * @description TODO
 * @date 2021/8/25 18:24
 */
@Slf4j
@Component
public class UserInfoInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader(CommonKey.USER_ID);
        String deptId = request.getHeader(CommonKey.DEPT_ID);
        String userName = request.getHeader(CommonKey.USER_NAME);
        String dept = request.getHeader(CommonKey.DEPT_IDS);
        if (StringUtils.isNotBlank(userId)) {
            setUserInfo(userName,Long.valueOf(userId),Long.valueOf(deptId),dept);
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
//            log.info("执行 == handler 清除前  after：{}",AuthUserInfo.getUser());
            AuthUserInfo.clearUser();
//            log.info("执行 == handler 清除后  after：{}",AuthUserInfo.getUser());
    }

    public void setUserInfo(String userName,Long userId,Long deptId, String dept) {
        List<Long> childes = new ArrayList<>();
        if (StringUtils.isNotBlank(dept)) {
            String[] depts = dept.split(",");
            for (String s : depts) {
                childes.add(Long.valueOf(s));
            }
        }
        UserInfo userInfo = UserInfo.builder()
                .userId(userId)
                .userName(userName)
                .deptId(deptId)
                .deptIds(childes)
                .build();
        AuthUserInfo.setUserInfo(userInfo);
    }

}
